﻿#coding=utf-8
import time
import random
import cgi
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm,PasswordChangeForm
from backend.forms import MyUserSettingsForm, MyUserCreationForm
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response, redirect
from django.utils import simplejson
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from backend.models import Member, Topic, FollowRelation, Mail
from django.utils.encoding import smart_unicode
from urllib2 import unquote
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Q
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.template import RequestContext as RC

def index(request):
  members = Member.objects.all()[:15]
  topics_all = Topic.objects.all().order_by('-created')
  paginator = Paginator(topics_all, 10)
  try:
    page = int(request.GET.get('page', '1'))
  except ValueError:
    page = 1
  try:
    topics = paginator.page(page)
  except (EmptyPage, InvalidPage):
    topics = paginator.page(paginator.num_pages)
  #print "1234566666"
  return render_to_response("index.html", {
    'members':members,
    'topics':topics,
    'paginator':paginator,
    'page_type':'index',
    'has_side':True,
    'view_user':request.user,
    },context_instance=RC(request))

@login_required
def favorite_view(request):
  topics_all = request.user.fav.all().order_by('-created')
  paginator = Paginator(topics_all, 10)
  try:
    page = int(request.GET.get('page', '1'))
  except ValueError:
    page = 1
  try:
    topics = paginator.page(page)
  except (EmptyPage, InvalidPage):
    topics = paginator.page(paginator.num_pages)

  return render_to_response("favorite.html",{
    'topics':topics,
    'page_type':'favorite',
    'paginator':paginator,
  },context_instance=RC(request))

@login_required
def setfav_view(request):
  """ 主页上的关注按钮的后台实现 根据ajax传递过来的值
      来往数据库表中插入或者删除用户的关注对象 
	  首先获取ajax提交的内容 提取出用户id 然后查找是否有该用户的关注 
	  有则remove 否则add
	  assert函数用来检测是否符合条件
  """
  assert(request.method =='POST' and request.is_ajax() == True)
  topic = Topic.objects.get(pk=int(request.POST['id']))
  if request.user in topic.favorites.all():
    topic.favorites.remove(request.user)
    response = HttpResponse('unfav')
  else:
    topic.favorites.add(request.user)
    response = HttpResponse('fav')
  return response


@login_required
def follow_member(request):
  """  该函数用来处理body里面的follow按钮点击进行关注或者取消关注 
  主要依据就是又有没关注的关系 如果关注的话就有该条信息 
  还是根据id字段来确定是哪一个用户
  assert函数用来检测是否符合条件
  """
  assert(request.method=='POST' and request.is_ajax()==True)
  try:
    print "hello!", request.raw_post_data
    follower = User.objects.get(pk=int(request.raw_post_data))
    my_follower_ship = FollowRelation.objects.filter(user=request.user, follower=follower)
    if len(my_follower_ship):
      my_follower_ship.delete()
    else:
      follow_relation = FollowRelation(user=request.user, follower=follower)
      follow_relation.save()
    return HttpResponse('success')
  except:
    return HttpResponse('fail')


@login_required
def delete_topic(request):
  """
  删除主页面的用户的自己所发的消息 从ajax获取用户的信息 
  如果有用户信息就删除该条信息 并返回success 否则返回false
  pk为主键所有信息都以这个为依据
  assert函数用来检测是否符合条件
  """
  assert(request.method=='POST' and request.is_ajax()==True)
  topic = Topic.objects.get(pk=int(request.POST['id']))
  if topic.author == request.user:
    topic.delete()
    return HttpResponse('success')
  else:
    return HttpResponse('fail')

	

@login_required
def post_topic(request):
  """
  用于接收用户最新发表的微博保存到数据库中 利用ajax传递 不刷新页面
  assert函数用来检测是否符合条件
  """
  assert(request.method=='POST' and request.is_ajax()==True)
  content = smart_unicode(request.raw_post_data)
  topic = Topic(content=content, author=request.user)
  topic.save()
  response = HttpResponse(cgi.escape(topic.content))
  return response

@login_required
def post_conversation(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  related_topic = Topic.objects.get(pk=int(request.POST['id']))
  topic = Topic(content=request.POST['content'], author=request.user,conversation=related_topic)
  topic.save()
  response = HttpResponse(cgi.escape(topic.content))
  return response


@login_required
def settings_view(request):
  try:
    info = Member.objects.get(user=request.user)
  except:
    info = Member(user=request.user)
  if request.method == 'POST':
    info_form = MyUserSettingsForm(request.POST, request.FILES, instance=info)
    password_form = PasswordChangeForm(request.user,request.POST)
    if info_form.is_valid():
      info_form = info_form.save()
    if password_form .is_valid():
      password_form.clean_old_password()
      password_form  = password_form.save()
    return HttpResponseRedirect("/settings/")
  else:
    info_form = MyUserSettingsForm(instance=info)
    password_form = PasswordChangeForm(request.user,request.GET)
  return render_to_response("settings.html", {
    'info_form':info_form,
    'password_form':password_form,
  },context_instance=RC(request))

@login_required
def self_view(request):
  """
  显示与用户有关的所有信息  用户自身的主页
  下面都有的就是对用户信息的处理 处理成为能够用模板进行传递的格式
  """
  if request.method == 'GET':
    try:
      followed = FollowRelation.objects.filter(user=request.user)[:12]
      follower = FollowRelation.objects.filter(follower=request.user)[:12]
    except:
      followed = 0
      follower = 0
    topics_all = Topic.objects.filter(author=request.user).order_by('-created')
    topics_count = topics_all.count()
    members = Member.objects.all()[:15]
    paginator = Paginator(topics_all, 10)
    try:
      page = int(request.GET.get('page', '1'))
    except ValueError:
      page = 1
    try:
      topics = paginator.page(page)
    except (EmptyPage, InvalidPage):
      topics = paginator.page(paginator.num_pages)

  return render_to_response("self.html", {
    'topics':topics,
    'members':members,
    'paginator':paginator,
    'follower':follower,
    'followed':followed,
    'page_type': 'self',
    'view_user':request.user,
    'has_side':True,
  },context_instance=RC(request))


@login_required
def main_view(request):
    if request.method == 'GET':
        try:
            #followed 我关注的人 follower 关注我的人
            followed = FollowRelation.objects.filter(user=request.user)
            follower = FollowRelation.objects.filter(follower=request.user)
        except:
            followed = 0
            follower = 0
         
        topics_all = list(Topic.objects.filter(Q(author=request.user)|Q(conversation__author=request.user)))
        for people in followed:            
            topics_all.extend(list(Topic.objects.filter(Q(author=people.follower))))
        
        topics_all = {}.fromkeys(topics_all).keys() #去掉重复的内容
        topics_all.sort(key=lambda x:x.created, reverse=True)
        
        topics_count = len(topics_all)
        members = Member.objects.all()[:15]
        paginator = Paginator(topics_all, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
            topics = paginator.page(paginator.num_pages)

    return render_to_response("mainpage.html", {
        'topics':topics,
        'members':members,
        'paginator':paginator,
        'follower':follower[:12],   #默认获取前12个，下同
        'followed':followed[:12],
        'page_type': 'mainpage',
        'view_user':request.user,
        'has_side':True,
        },context_instance=RC(request))


@login_required
def member_view(request, user_name):
  """
  如果是自己，则跳转到我的微博页面 显示与用户有关的所有信息
  下面都有的就是对用户信息的处理 处理成为能够用模板进行传递的格式
  """
  if user_name.encode("utf-8") == str(request.user):
    return redirect('/member/')
  if request.method == 'GET':
    view_user = User.objects.get(username=user_name)
    my_follower_ship = FollowRelation.objects.filter(user=request.user).filter(follower=view_user)
    topics_all = Topic.objects.filter(author=view_user).order_by('-created')
    topics_count = topics_all.count()
    paginator = Paginator(topics_all, 10)
    members = Member.objects.all()[:15]
    try:
      followed = FollowRelation.objects.filter(user=view_user)[:12]
      follower = FollowRelation.objects.filter(follower=view_user)[:12]
    except:
      followed = 0
      follower = 0
    try:
      page = int(request.GET.get('page', '1'))
    except ValueError:
      page = 1
    try:
      topics = paginator.page(page)
    except (EmptyPage, InvalidPage):
      topics = paginator.page(paginator.num_pages)
  return render_to_response("member.html", {
    'topics':topics,
    'members':members,
    'topics_count':topics_count,
    'view_user':view_user,
    'nickname':view_user.get_profile().nickname,
    'is_followed':len(my_follower_ship),
    'page_type':'member',
    'follower':follower,
    'followed':followed,
    'has_side':True,
  },context_instance=RC(request))

def get_userinfo(me, person):
    #获取用户信息的函数 供多个函数模块调用
	
    protrait_url = person.get_profile().gen_protrait()
    gender = person.get_profile().gen_gender()
    sign = person.get_profile().sign
    is_followed = len(FollowRelation.objects.filter(user=me).filter(follower=person))
    people = {"username":person.username, "date_joined":person.date_joined,\
        "sign":sign, "is_followed":is_followed, "protrait_url":protrait_url,\
        'gender':gender, "id":person.id}
    
    return people
  
  
@login_required
def search_view(request):
    #搜索函数 用于用户的对所需要的信息的检索
    searchtype=""
    topics_all=[]
    searchstrs=[]
    peoples_all=[]
    
    if request.method == 'POST':
        if request.POST.has_key("search_type"):
            searchtype = request.POST["search_type"]
        searchstrs = request.POST["searchstr"]
        if searchstrs == "":    #如果搜索为空，返回我的主页
            return redirect('/search/')
        else:
            searchstrs = searchstrs.split()
    
    if searchtype == "index":
        for search_key in searchstrs:
            topics_all.extend(list(Topic.objects.filter(content__contains=search_key)))

    elif searchtype == "mainpage":
        try:
            #followed 我关注的人
            followed = FollowRelation.objects.filter(user=request.user)
        except:
            followed = 0
        
        for search_key in searchstrs:
            topics_all.extend(list(Topic.objects.filter(Q(author=request.user)
                        & Q(content__contains=search_key))))
            for people in followed:            
                topics_all.extend(list(Topic.objects.filter(Q(author=people.follower)
                        & Q(content__contains=search_key))))
                        
    elif searchtype == "self":
        for search_key in searchstrs:
            topics_all.extend(list(Topic.objects.filter(Q(author=request.user)
                        & Q(content__contains=search_key))))
    
    elif searchtype == "member":
        users=[]
        for search_key in searchstrs:
            users.extend(list(Member.objects.filter(user__username__contains=search_key)))
        users = {}.fromkeys(users).keys() #去掉重复的内容
        
        for person in users:
            people = get_userinfo(request.user, person.user)
            peoples_all.append(people)
    
    elif searchtype.startswith("follow"):
		#对follow的搜索
        users_followed=[]
        users_follower=[]
        for search_key in searchstrs:
            users_followed = list(FollowRelation.objects.filter(Q(user=request.user) & Q(follower__username__contains=search_key)))
            users_follower = list(FollowRelation.objects.filter(Q(follower=request.user) & Q(user__username__contains=search_key)))
        
        users=[]
        for person in users_followed:
            users.append(person.follower)
        for person in users_follower:
            users.append(person.user)
            
        users = {}.fromkeys(users).keys() #去掉重复的内容
        for person in users:
            people = get_userinfo(request.user, person)
            peoples_all.append(people)
            
    else:
        for search_key in searchstrs:
            topics_all.extend(list(Topic.objects.filter(content__contains=search_key)))
    
    if searchtype == "member" or searchtype.startswith("follow"):
        paginator = Paginator(peoples_all, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            peoples = paginator.page(page)
        except (EmptyPage, InvalidPage):
            peoples = paginator.page(paginator.num_pages)
        
        return render_to_response("search.html",{
        'peoples':peoples,
        'paginator':paginator,
        'view_user':request.user,
        'page_type':'search',
        'search_type':'user',
        'has_side':True,
        },context_instance=RC(request))
    
    else:
        topics_all = {}.fromkeys(topics_all).keys() #去掉重复的内容
        topics_all.sort(key=lambda x:x.created, reverse=True)
            
        paginator = Paginator(topics_all, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
            topics = paginator.page(paginator.num_pages)

        return render_to_response("search.html",{
        'topics':topics,
        'paginator':paginator,
        'view_user':request.user,
        'page_type':'search',
        'search_type':'topic',
        'has_side':True,
        },context_instance=RC(request))
    
		
		
@login_required        
def comments_view(request, option="in"):
    try:
        #followed 我关注的人 follower 关注我的人
        followed = FollowRelation.objects.filter(user=request.user)
        follower = FollowRelation.objects.filter(follower=request.user)
    except:
        followed = 0
        follower = 0
        
    if option == "in":
        #给我的评论
        topics_all = list(Topic.objects.filter(conversation__author=request.user))
        topics_all.sort(key=lambda x:x.created, reverse=True)
        #分页的数目为10条一页
        paginator = Paginator(topics_all, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
            topics = paginator.page(paginator.num_pages)

        return render_to_response("comments.html", {
            'topics':topics,
            'paginator':paginator,
            'follower':follower[:12],   #默认获取前12个，下同
            'followed':followed[:12],
            'page_type': 'comments_in',
            'view_user':request.user,
            'has_side':True,
            },context_instance=RC(request))
    
    else:
        #我发出的评论
        topics_all = list(Topic.objects.filter(Q(author=request.user)&Q(conversation__author__isnull=False)))
        topics_all.sort(key=lambda x:x.created, reverse=True)
        #分页的数目为10条一页
        paginator = Paginator(topics_all, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
            topics = paginator.page(paginator.num_pages)

        return render_to_response("comments.html", {
            'topics':topics,
            'paginator':paginator,
            'follower':follower[:12],   #默认获取前12个，下同
            'followed':followed[:12],
            'page_type': 'comments_out',
            'view_user':request.user,
            'has_side':True,
            },context_instance=RC(request))
 

 
@login_required        
def follow_view(request, option="in"):   
    """
	in 为关注我的人  用下面的if中的语句处理函数 否则用else里的语句处理即我关注的人
	然后返回查询的信息
    """     
    if option == "in":
        try:
            #followers 关注我的人
            followers = FollowRelation.objects.filter(follower=request.user)
        except:
            followers = 0
          
        if followers == 0:
            return render_to_response("follow.html", {
            'page_type': 'follow_in',
            'view_user':request.user,
            'has_side':True,
            },context_instance=RC(request))
        
        peoples_all=[]
        for follower in followers:
            people = get_userinfo(request.user, follower.user)
            peoples_all.append(people)
    
    else:
        try:
            #followers 我关注的人
            followeds = FollowRelation.objects.filter(user=request.user)
        except:
            followeds = 0
            
        if followeds == 0:
            return render_to_response("follow.html", {
            'page_type': 'follow_out',
            'view_user':request.user,
            'has_side':True,
            },context_instance=RC(request))
        
        peoples_all=[]
        for followed in followeds:
            people = get_userinfo(request.user, followed.follower)
            peoples_all.append(people)
            
    paginator = Paginator(peoples_all, 10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        peoples = paginator.page(page)
    except (EmptyPage, InvalidPage):
        peoples = paginator.page(paginator.num_pages)
    
    return render_to_response("follow.html", {
        'peoples':peoples,
        'paginator':paginator,
        'page_type': option=='in' and 'follow_in' or 'follow_out',
        'view_user':request.user,
        'has_side':True,
        },context_instance=RC(request))
        